package ru.autofan.aop;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ru.autofan.logic.LoginService;
import ru.autofan.logic.ServiceLocator;

public class RequestInterceptor implements HandlerInterceptor {

	public static ThreadLocal<HttpSession> httpSessionHolder = new ThreadLocal<HttpSession>();
	
    private ServiceLocator serviceLocator;

    public LoginService getLoginService() {
		return this.serviceLocator.getService(LoginService.class);
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		httpSessionHolder.set(null);
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}

	private String[] checkCookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String email = null;
		String password = null;
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals("email")) {
					email = c.getValue();
				}
				if (c.getName().equals("password")) {
					password = c.getValue();
				}
			}
		}
		return new String[] { email, password };
	}

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
        
		httpSessionHolder.set(request.getSession());
        /** Validate local thread roles with logged user roles */
        getLoginService().validate();
		
        String[] emailAndPassword = checkCookies(request);
		if (!getLoginService().isLogged()
				&& emailAndPassword[0] != null && emailAndPassword[1] != null) {
			getLoginService().login(emailAndPassword[0],
					emailAndPassword[1]);
		}

		return true;
	}

	public void setServiceLocator(ServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}

}
